# This test script performs the second of the benchmarks presented in
# the paper I am submitting to mobisys '10. 
#
# The benchmark performs a brightness adjustment to the input image. 
# The scheduler in use is the adaptive, combined scheduler.
# This test shows two things:
#    1) It measures the scheduling overhead (the frist token on each line)
#    2) It shows that the adaptive profile works.
#
# The input images used in the paper can be found in testdata/percom.

from __future__ import with_statement
import sys
import scavenger
from time import sleep, time

# Check command line args.
if len(sys.argv) < 4:
    print 'Usage: mobisys1.py imagefile -s scheduler [-i iterations]'
    sys.exit(1)

# Find out which scheduler to use.
scheduler = sys.argv[sys.argv.index('-s') + 1]
if not scheduler in ('pc', 'tc', 'adaptive'):
    print 'Invalid scheduler. Valid values are pc, tc, and adaptive.'
    sys.exit(1)

# Read in the image file.
with open(sys.argv[1], 'rb') as infile:
    image = infile.read()

# Check whether a number of test iterations is given.
iterations = 1
if '-i' in sys.argv:
    iterations = int(sys.argv[sys.argv.index('-i') + 1])

# Sleep for a little while to make sure that we discover
# the available surrogates.
sleep(2.0)

@scavenger.lprofilescavenge('len(#0)')
def lbrightness(image, factor):
    from PIL import Image, ImageEnhance
    from StringIO import StringIO
    sio = StringIO(image)
    pil_image = Image.open(sio)
    new_image = ImageEnhance.Brightness(pil_image).enhance(factor)
    sio = StringIO()
    new_image.save(sio, pil_image.format, quality=95)
    return sio.getvalue()

@scavenger.gprofilescavenge('len(#0)')
def gbrightness(image, factor):
    from PIL import Image, ImageEnhance
    from StringIO import StringIO
    sio = StringIO(image)
    pil_image = Image.open(sio)
    new_image = ImageEnhance.Brightness(pil_image).enhance(factor)
    sio = StringIO()
    new_image.save(sio, pil_image.format, quality=95)
    return sio.getvalue()

@scavenger.aprofilescavenge('len(#0)', 'len(#0)')
def abrightness(image, factor):
    from PIL import Image, ImageEnhance
    from StringIO import StringIO
    sio = StringIO(image)
    pil_image = Image.open(sio)
    new_image = ImageEnhance.Brightness(pil_image).enhance(factor)
    sio = StringIO()
    new_image.save(sio, pil_image.format, quality=95)
    return sio.getvalue()

function = None
if scheduler == 'pc':
    function = lbrightness
elif scheduler == 'tc':
    function = gbrightness
else:
    function = abrightness

# Run the test!
for x in range(0, iterations):
    start = time()
    try:
        function(image, 1.3)
    except:
        print 'error',
    stop = time()
    print stop - start

scavenger.shutdown()
